package samples.chapter04;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController()
@RequestMapping("/chapter04")
public class Chapter04FileUploadController {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");

    @PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request) {
        String realPath = request.getServletContext().getRealPath("uploads/");
        String format = dateFormat.format(new Date());
        File folder = new File(realPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."));
        try {
            File dest = new File(folder, newName);
            file.transferTo(dest);
            return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +
                    request.getContextPath() + "/uploads/" + format + newName;
        } catch (IOException e) {
            return e.getMessage();
        }
    }

    @PostMapping("/uploads")
    public String uploads(MultipartFile[] files, HttpServletRequest request) {
        throw new RuntimeException("not implemented");
    }
}
